package quickAdd.client;

import com.google.gwt.user.client.ui.*;

/**
 * The login panel.
 */
public class LoginPanel extends HorizontalPanel implements Auth.AuthorizationComplete
{
    Auth auth;
    TextBox email = new TextBox();
    PasswordTextBox passwd = new PasswordTextBox();
    Button login = new Button("Login");

    public LoginPanel( Auth auth )
    {
        this.auth = auth;
        auth.addListener( this );
        setStyleName( "quickadd-LoginPanel");

        setSpacing(7);
        add(new Label("Email:"));
        add( email );

        add(new Label("Password:"));
        passwd.addKeyboardListener( new KeyboardListener()
        {
            public void onKeyDown( Widget sender, char keyCode, int modifiers ) {  }
            public void onKeyPress( Widget sender, char keyCode, int modifiers ) {
                if ( keyCode == KeyboardListener.KEY_ENTER )
                    login();
            }
            public void onKeyUp( Widget sender, char keyCode, int modifiers ) {  }
        });
        add( passwd );

        login.addClickListener( new ClickListener() {
            public void onClick( Widget sender ) {
                login();
            }
        });

        add(login);
    }
    
    private void login() {
        setButtonState(false);
        auth.setEmail( email.getText() );
        auth.setPasswd( passwd.getText() );
        auth.authenticate();
    }

    private void setButtonState( boolean enabled ) {
        login.setEnabled( enabled );
        String styleName =
            enabled ? "quickadd-ButtonEnabled" : "quickadd-ButtonDisabled";
        login.setStyleName( styleName );
    }

    public void authorizationBeginning() {
        setWait( true );
        login.addStyleName( "quickadd-Wait" );
    }

    public void authorizationComplete() {
        setWait( false );
        setButtonState( true );
    }
    public void authorizationFailed() {
        setWait( false );
        passwd.setSelectionRange( 0, passwd.getText().length()-1) ;
        setButtonState(true);
    }

    private void setWait( boolean wait ) {
        if ( wait ) {
            addStyleName( "quickadd-Wait" );
            //Should all of these be necessary?
            login.addStyleName( "quickadd-Wait" );
            email.addStyleName( "quickadd-Wait" );
            passwd.addStyleName( "quickadd-Wait" );
        } else {
            removeStyleName( "quickadd-Wait" );
            login.removeStyleName( "quickadd-Wait" );
            email.removeStyleName( "quickadd-Wait" );
            passwd.removeStyleName( "quickadd-Wait" );
        }
    }
}
